package yun.web.activerecord.dialect.pg;

import yun.web.activerecord.generator.BaseModelGenerator;
import yun.web.activerecord.generator.TableMeta;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class PGBaseModelGenerator extends BaseModelGenerator {

    public PGBaseModelGenerator(String baseModelPackageName, String baseModelOutputDir) {
        super(baseModelPackageName, baseModelOutputDir);
        setTemplate("yun/web/activerecord/dialect/pg/base_model_template.jf");
    }

    @Override
    protected void writeToFile(TableMeta tableMeta) {
        PGTableMeta pgTableMeta = (PGTableMeta) tableMeta;
        File dir = new File(baseModelOutputDir + File.separator + pgTableMeta.schema_name + File.separator + "base");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        OutputStreamWriter osw = null;
        try {
            osw = new OutputStreamWriter(new FileOutputStream(new File(dir, pgTableMeta.baseModelName + ".java")), "UTF-8");
            osw.write(pgTableMeta.baseModelContent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                osw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
